package spring.cloud.tasks.executor.name_space.executor.task.task_listener.task_statistics;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.common.node.TaskNodePath;
import spring.cloud.tasks.executor.name_space.executor.task.task_listener.TreeCacheListener;
import spring.cloud.tasks.executor.utils.LogUtils;

@Slf4j
@Setter
@Getter
class TaskResetStatisticsListener extends TreeCacheListener {

    private final TaskResetStatisticsListenerHolder resetListenerHolder;

    public TaskResetStatisticsListener(TaskResetStatisticsListenerHolder resetListenerHolder) {
        this.resetListenerHolder = resetListenerHolder;
    }

    @Override
    protected void dataChanged(CuratorFramework curatorFramework, String path, TreeCacheEvent treeCacheEvent) {
        if (resetListenerHolder.isShutdown) {
            return;
        }
        if (TaskNodePath.getTaskNodePath(resetListenerHolder.taskId, TaskStatisticsNode.reset_statistics).equals(path) && (TreeCacheEvent.Type.NODE_ADDED == treeCacheEvent.getType() || TreeCacheEvent.Type.NODE_UPDATED == treeCacheEvent.getType())) {
            if (TaskStatisticsResetType.reset_total_count_delta_and_failure_count_delta.equals(new String(treeCacheEvent.getData().getData()))) {
                LogUtils.info(log, resetListenerHolder.taskId, "job:{} reset anaylse count.", resetListenerHolder.taskId);
                TaskStatistics.resetTotalCountDeltaAndFailureCountDelta(resetListenerHolder.taskId, resetListenerHolder.executorId);
            } else if (TaskStatisticsResetType.reset_success_failure_count.equals(new String(treeCacheEvent.getData().getData()))) {
                LogUtils.info(log, resetListenerHolder.taskId, "job:{} reset success/failure count", resetListenerHolder.taskId);
                TaskStatistics.resetSuccessFailureCount(resetListenerHolder.taskId, resetListenerHolder.executorId);
            }
        }
    }
}
